from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token, csrf_exempt
from django.contrib.auth.models import User
from django.contrib.auth import get_user
from django.core.exceptions import FieldDoesNotExist
import json
from django.http import HttpResponse

# Create your views here.


def user_center(request):
    """用户中心"""
    user = request.user
    user_info = {
        "username": user.username,
        "phone": user.profile.phone,
        "account_type": user.profile.get_account_type_display(),
        "email": user.email,
        "company": user.profile.company,
        "date_joined": user.date_joined.strftime("%Y-%m-%d"),
    }

    return render(request, "user_center.html", {"user_info": user_info})


@csrf_exempt
def update_user_info(request):
    from Profile.models import Profile
    field = request.POST.get('field', '')
    update_val = request.POST.get('update_val', '')

    user = get_user(request)
    result = {"code": "-1", "message": "error"}

    try:
        Profile.objects.filter(user=user).update(**{field: update_val})
    except FieldDoesNotExist:
        try:
            User.objects.filter(pk=request.user.id).update(**{field: update_val})
        except FieldDoesNotExist:
            raise
        else:
            result["code"], result["message"] = "1", "success"
    except Exception:
        pass
    else:
        result["code"], result["message"] = "1", "success"

    return HttpResponse(json.dumps(result))
